package com.kele.es_project.service;

import com.alibaba.fastjson.JSON;
import com.kele.es_project.pojo.Content;
import com.kele.es_project.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2021/4/6
 * @Content:
 * @Description：
 */
@Service
public class ContentService {

    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;


    public static void main(String[] args) throws Exception {
        System.out.println(new ContentService().pareContent("java"));
    }

    //将数据放入索引中
    public  boolean pareContent(String keyword) throws Exception{
        List<Content> list = new HtmlParseUtils().pareJD(keyword);

        //批量插入
        BulkRequest bulkRequest=new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i <list.size() ; i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        boolean hasFailures = bulk.hasFailures();


        return hasFailures;

    }

    //搜索
    public  List<Map<String,Object>> search(String keyword, int pageNo, int pageSize) throws Exception{
        if (pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest=new SearchRequest("jd_goods");
        SearchSourceBuilder builder=new SearchSourceBuilder();
        TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
        builder.query(title);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // 支持多个高亮设置为true, 比如一段文字有多个java单词, 若设置false, 则只高亮第一个java单词
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(builder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);



        List<Map<String,Object>> list=new ArrayList<>();
        //解析结果
        for (SearchHit searchHit : search.getHits().getHits()) {

            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();

            // 解析高亮字段
            Map<String, HighlightField> highlightFieldMap = searchHit.getHighlightFields();
            HighlightField highlightField = highlightFieldMap.get("title");
            if (Objects.nonNull(highlightField)) {
                Text[] fragments = highlightField.fragments();
                StringBuilder newTitle = new StringBuilder();
                for (Text fragment : fragments) {
                    newTitle.append(fragment.string());
                }
                // 替换即可
                sourceAsMap.put("title", newTitle);
            }
            list.add(sourceAsMap);

        }
        return list;
    }
}
